require('dotenv').config();
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const axios = require('axios');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// 静态文件服务
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.json());

// Deepseek API 配置
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';

// Socket.io 连接处理
io.on('connection', (socket) => {
    console.log('用户已连接');

    socket.on('sendMessage', async (message) => {
        console.log('收到用户消息:', message);
        try {
            console.log('准备发送到 Deepseek API...');
            const response = await axios({
                method: 'post',
                url: DEEPSEEK_API_URL,
                data: {
                    model: "deepseek-chat",
                    messages: [
                        { role: "user", content: message }
                    ],
                    temperature: 0.7,
                    max_tokens: 2000,
                    stream: true
                },
                headers: {
                    'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
                    'Content-Type': 'application/json',
                    'Accept': 'text/event-stream'
                },
                responseType: 'stream'
            });
            
            console.log('API 请求成功，开始处理流式响应...');
            socket.emit('receiveMessage', { type: 'start' });

            let buffer = '';
            response.data.on('data', chunk => {
                const chunkText = chunk.toString();
                console.log('原始数据块:', chunkText);
                buffer += chunkText;

                const lines = buffer.split('\n');
                buffer = lines.pop(); // 保留最后一个不完整的行

                for (const line of lines) {
                    const trimmedLine = line.trim();
                    if (!trimmedLine) continue;
                    if (trimmedLine === 'data: [DONE]') {
                        console.log('收到结束标记');
                        continue;
                    }
                    if (!trimmedLine.startsWith('data: ')) {
                        console.log('跳过非数据行:', trimmedLine);
                        continue;
                    }
                    
                    try {
                        const data = JSON.parse(trimmedLine.slice(6));
                        console.log('解析的数据:', data);
                        if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
                            const content = data.choices[0].delta.content;
                            console.log('发送内容片段:', content);
                            socket.emit('receiveMessage', {
                                type: 'chunk',
                                content: content
                            });
                        }
                    } catch (e) {
                        console.error('解析流数据错误:', e, '原始行:', trimmedLine);
                    }
                }
            });

            response.data.on('end', () => {
                console.log('流式响应结束');
                socket.emit('receiveMessage', { type: 'end' });
            });

        } catch (error) {
            console.error('Deepseek API 错误:', error.message);
            if (error.response) {
                console.error('错误详情:', error.response.data);
                console.error('状态码:', error.response.status);
                console.error('响应头:', error.response.headers);
            } else {
                console.error('完整错误对象:', error);
            }
            socket.emit('error', '抱歉，处理您的消息时出现错误');
        }
    });

    socket.on('disconnect', () => {
        console.log('用户已断开连接');
    });
});

const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});